//
//  ShoppingCartVC.m
//  phmall
//
//  Created by admin on 2017/11/3.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "ShoppingCartVC.h"
#import "ShoppingCartCell.h"
#import "CommodityDetailsVC.h"
#import "ShoppingCartEditCell.h"
#import "DynamicVC.h"
#import "OrderModel.h"
#import "CartModel.h"
#import "HTPlistTool.h"
#import "ConfirmAnOrderVC.h"
#define TAG_CELLBTN 0x1000
#define TAG_HEADERBTN 0x0100

@interface ShoppingCartVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate> {
    
    /** 选择总价*/
    UILabel *_totalLabel;
    /** 是否点击页面右上角编辑按钮*/
    BOOL _isPressEditButton;
    /** rightBarButtonItem按钮文字*/
    NSString *_rightBarButtonItemTitle;
    
    UIButton *account;
    
    UIButton *select;
    
    UIBarButtonItem *rightBar;
    
    UIView *bottom;
}
/** 购物车清单本地存储地址*/
@property (nonatomic, strong) NSString *path;
/** 购物车清单*/
@property (nonatomic, strong)NSMutableArray *cartArray;
@property (nonatomic, strong)NSMutableDictionary *numDict;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)MBProgressHUD *hud;
@end

@implementation ShoppingCartVC

- (void)loadDataWithCart:(BOOL)reload{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"cart"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
    
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                YYCache *cache = [YYCache cacheWithName:@"cart"];
                [cache setObject:responseDict[@"data"] forKey:@"list"];
                if (data.count==0) {
                    _rightBarButtonItemTitle=Localized(@"编辑");
                    [account setTitle:Localized(@"结算") forState:UIControlStateNormal];
                    [self.tableview.mj_header endRefreshing];
                    [self.tableview.mj_footer endRefreshingWithNoMoreData];
                    if (reload) {
                        [self.cartArray removeAllObjects];
                        [self updateBottomView];
                        [self.tableview reloadData];
                    }
                }else{
                    [self analysisDataWithCartArray:data];
                }
            }
        }else{
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        [self.cartArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.tableview reloadData];
        [self.tableview.mj_header endRefreshing];
    }];
}
- (void)analysisDataWithCartArray:(NSMutableArray *)array{
    [self.cartArray removeAllObjects];
    for (NSMutableArray *data in array) {
        NSMutableDictionary *dataDict=[[NSMutableDictionary alloc]init];
        [dataDict setObject:data forKey:@"goods"];
        CartModel *model=[CartModel yy_modelWithDictionary:dataDict];
        select.selected = NO;
        [self.cartArray addObject:model];
    }
    [self.tableview.mj_header endRefreshing];
    [self updateBottomView];
    [self.tableview reloadData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor  orangeColor];
    //导航栏字体和颜色
    NSMutableDictionary *navDic=@{}.mutableCopy;
    navDic[NSFontAttributeName]=[UIFont systemFontOfSize:20];
    navDic[NSForegroundColorAttributeName]=[UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:navDic];
    
    YYCache *cache = [YYCache cacheWithName:@"cart"];
    if ([cache containsObjectForKey:@"list"]) {
        NSMutableArray *index = (NSMutableArray *)[cache objectForKey:@"list"];
        [self analysisDataWithCartArray:index];
        [self.tableview reloadData];
    }
    
    [self loadDataWithCart:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    self.title=Localized(@"购物车");
    self.emptyType=EmptyDataSetNoData;
   


    // Do any additional setup after loading the view.
    _rightBarButtonItemTitle = Localized(@"编辑");
    rightBar = [[UIBarButtonItem alloc]initWithTitle:_rightBarButtonItemTitle style:UIBarButtonItemStyleDone target:self action:@selector(editAllGoods:)];
    [rightBar setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.rightBarButtonItem=rightBar;
  

    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    if (self.BACK) {
        self.navigationItem.leftBarButtonItem=leftBar;
    }
    
    
    if (@available(iOS 11.0, *)) {
        self.tableview.estimatedRowHeight = 0;
        self.tableview.estimatedSectionFooterHeight = 0;
        self.tableview.estimatedSectionHeaderHeight = 0;
        self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.emptyType=EmptyDataSetNone; 
    [self.view addSubview:self.tableview];
    [self.tableview setContentOffset:CGPointZero animated:YES];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.offset(0);
        make.right.offset(0);
        if (self.BACK) {
            make.bottom.offset(-49-self.tabBar_height);
        }else{
            make.bottom.offset(-49);
        }
    }];
    [self setBottomView];
    [self refreshCart];
    [self updateBottomView];
   
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];

}
-(void)HeaderRefresh{
    [self loadDataWithCart:NO];
}
-(void)setBottomView{
    
    bottom=[[UIView alloc]init];
    [self.view addSubview:bottom];
    bottom.backgroundColor=[UIColor whiteColor];
    [bottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(49);
        if (self.BACK) {
            make.bottom.offset(-self.tabBar_height);
        }else{
            make.bottom.offset(0);
        }
    }];
    
    select=[UIButton buttonWithType:UIButtonTypeCustom];
    [select setImage:[UIImage imageNamed:[NSString stringWithFormat:@"未选中"]] forState:UIControlStateNormal];
    [select setImage:[UIImage imageNamed:[NSString stringWithFormat:@"选中"]] forState:UIControlStateSelected];
    [select addTarget:self action:@selector(clickAllChooseButton:) forControlEvents:UIControlEventTouchUpInside];
    [bottom addSubview:select];
    [select mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottom);
        make.left.offset(5);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    
    UILabel *allSlect=[[UILabel alloc]init];
    [bottom addSubview:allSlect];
    allSlect.text=Localized(@"全选");
    allSlect.font=[UIFont systemFontOfSize:15];
    [allSlect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(select.mas_right).offset(5);
        make.centerY.equalTo(select);
    }];
    
    account=[[UIButton alloc]init];
    [bottom addSubview:account];
    [account setTitle:Localized(@"结算") forState:UIControlStateNormal];
    [account addTarget:self action:@selector(settlement) forControlEvents:UIControlEventTouchUpInside];
    account.titleLabel.font=[UIFont systemFontOfSize:18];
    account.backgroundColor=[UIColor orangeColor];
    [account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.offset(0);
        make.width.offset(100);
    }];
    
    UILabel *barring=[[UILabel alloc]init];
    [bottom addSubview:barring];
    barring.text=Localized(@"不含运费");
    barring.font=[UIFont systemFontOfSize:13];
    barring.textColor=[UIColor colorWithHexString:@"#adadad"];
    [barring mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(account.mas_left).offset(-10);
        make.top.equalTo(bottom).offset(5);
    }];
    
    _totalLabel=[[UILabel alloc]init];
    _totalLabel.textColor=[UIColor orangeColor];
    _totalLabel.font=[UIFont systemFontOfSize:15];
    [bottom addSubview:_totalLabel];
    [_totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(account.mas_left).offset(-10);
        make.bottom.equalTo(bottom).offset(-5);
    }];
    
    UIView *line=[[UIView alloc]init];
    [bottom addSubview:line];
    line.backgroundColor=[UIColor colorWithHexString:@"#ECEBEC"];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(0.5);
    }];
}
-(void)settlement{
    BOOL isEdit = [account.titleLabel.text isEqualToString:Localized(@"结算")];
    
    if (isEdit) {
        NSMutableArray *orderArray=[[NSMutableArray alloc]init];
        for (CartModel *cartModel in self.cartArray) {
            OrderModel *order=[[OrderModel alloc]init];
            NSMutableArray *goodsArray=[[NSMutableArray alloc]init];
            NSString *shop_name=[[NSString alloc]init];
            NSString *shop_id=[[NSString alloc]init];
            for (CartDetailModel *detailModel in cartModel.goods) {
                if (detailModel.chooseState) {
                    GoodsListModel *model=[[GoodsListModel alloc]init];
                    model.goods_name=detailModel.goods_name;
                    model.rest_price=detailModel.cart_price;
                    model.buy_price=detailModel.rest_price;
                    model.buy_number=detailModel.cart_num;
                    model.goods_attr=detailModel.attr_txt;
                    model.g_uid=detailModel.uid;
                    model.goods_file=detailModel.goods_file1;
                    [goodsArray addObject:model];
                    shop_name=detailModel.shop_name;
                    shop_id=detailModel.shop_uid;
                }
            }
            if (goodsArray.count!=0) {
                order.goods_list=goodsArray;
                order.shop_name=shop_name;
                order.m_uid=shop_id;
                order.all_number=[NSString stringWithFormat:@"%lu",(unsigned long)goodsArray.count];
                [orderArray addObject:order];
            }
        }
        if (orderArray.count==0) {
             [PublicClass ProgressHUDModeText:Localized(@"请选择商品") andTime:2 ];
            return;
        }
        
        
        self.hidesBottomBarWhenPushed=YES;
        ConfirmAnOrderVC *sear=[[ConfirmAnOrderVC alloc] init];
        sear.orderArray=orderArray;
        [self.navigationController pushViewController:sear animated:YES];
        self.hidesBottomBarWhenPushed=NO;
    }else{
       
        for (CartModel *cartModel in self.cartArray) {
            for (CartDetailModel *detailModel in cartModel.goods) {
                if (detailModel.chooseState) {
                    [self loadDataWithCartDetele:detailModel.uid];
                }
            }
        }
        
    }
    
}

#pragma mark UITableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    self.navigationItem.rightBarButtonItem.title = self.cartArray.count != 0 ? _rightBarButtonItemTitle : @"";
    return self.cartArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CartModel *model = self.cartArray[section];
    //    NSArray *goodsArr = array;
    return model.goods.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CartModel *cartModel = self.cartArray[indexPath.section];
    CartDetailModel *model=cartModel.goods[indexPath.row];
 
    cartModel.isEdit = [_rightBarButtonItemTitle isEqualToString:Localized(@"编辑")];

    if (!cartModel.isEdit) {
        ShoppingCartEditCell *cell=[ShoppingCartEditCell theShareCellWithTableView:tableView];
        cell.numberButton.resultBlock = ^(NSInteger num ,BOOL increaseStatus){
            NSLog(@"%ld,%@",num,indexPath);
            [self changeGoodsNumber:num cellForRowAtIndexPath:indexPath];
        };
        cell.model=model;
        cell.numberButton.tag=indexPath.section * TAG_CELLBTN + indexPath.row;
        cell.select.tag = indexPath.section * TAG_CELLBTN + indexPath.row;
        cell.select.selected=model.chooseState;
        cell.edit.tag = indexPath.section * TAG_CELLBTN + indexPath.row;
        [cell.select addTarget:self action:@selector(clickSingleChooseButton:) forControlEvents:UIControlEventTouchUpInside];
        [cell.edit addTarget:self action:@selector(cartDetele:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        ShoppingCartCell *cell=[ShoppingCartCell theShareCellWithTableView:tableView];
        cell.model=model;
        cell.select.tag = indexPath.section * TAG_CELLBTN + indexPath.row;
        cell.select.selected=model.chooseState;
        [cell.select addTarget:self action:@selector(clickSingleChooseButton:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartModel *model=self.cartArray[indexPath.section];
    CartDetailModel *detailModel=model.goods[indexPath.row];
    self.hidesBottomBarWhenPushed=YES;
    CommodityDetailsVC *deta=[[CommodityDetailsVC alloc] init];
    deta.uid=detailModel.g_uid;
    [self.navigationController pushViewController:deta animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartModel *cartModel = self.cartArray[indexPath.section];
    if(!cartModel.isEdit){
        return NO;
    }else{
        return YES;
    }

}

//-(void)goToShop{
////    CartModel *model=self.cartArray[indexPath.section];
////    CartDetailModel *detailModel=model.goods.f;
//    self.hidesBottomBarWhenPushed=YES;
//    DynamicVC *dynamic=[[DynamicVC alloc]init];
////    dynamic.uid=self.model.supplier_id;
//    [self.navigationController pushViewController:dynamic animated:YES];
//}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
//    NSLog(@"%f",scrollView.contentOffset.y);
    
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:Localized(@"删除") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        CartModel *cartModel = self.cartArray[indexPath.section];
        CartDetailModel *dataolModel=cartModel.goods[indexPath.row];
        [self loadDataWithCartDetele:dataolModel.uid];
    }];
    UITableViewRowAction *collectAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:Localized(@"收藏") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    collectAction.backgroundColor = [UIColor orangeColor];
    
    return @[deleteAction];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0,10,self.view.frame.size.width,40)];
    headerView.backgroundColor=[UIColor whiteColor];
    
    CartModel *cartModel = self.cartArray[section];
    
    UIButton *select=[UIButton buttonWithType:UIButtonTypeCustom];
    [select setImage:[UIImage imageNamed:[NSString stringWithFormat:@"未选中"]] forState:UIControlStateNormal];
    [select setImage:[UIImage imageNamed:[NSString stringWithFormat:@"选中"]] forState:UIControlStateSelected];
    [select addTarget:self action:@selector(clickShopAllChooseButton:) forControlEvents:UIControlEventTouchUpInside];
    select.selected=cartModel.chooseState;
    select.tag=section*TAG_CELLBTN;
    [headerView addSubview:select];
    [select mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView).with.offset(5);
        make.left.equalTo(headerView).with.offset(5);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    
    UIImageView *logo=[[UIImageView alloc]init];
    logo.image=[UIImage imageNamed:@"图标"];
    [headerView addSubview:logo];
    [logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(select);
        make.width.height.offset(20);
        make.left.equalTo(select.mas_right).with.offset(5);
    }];
    
    UILabel *name=[UILabel new];
    if (self.cartArray.count!=0) {
        CartDetailModel *model=cartModel.goods[0];
        name.text=model.shop_name;
    }
    name.font=[UIFont systemFontOfSize:15];
    [headerView addSubview:name];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(select);
        make.left.equalTo(logo.mas_right).with.offset(5);
    }];
    
    UIImageView *leave=[[UIImageView alloc]init];
    leave.image=[UIImage imageNamed:@"前往"];
    [headerView addSubview:leave];
    [leave mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(select);
        make.width.height.offset(15);
        make.left.equalTo(name.mas_right).with.offset(5);
    }];
    
    UIView *head=[UIView new];
    head.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [headerView addSubview:head];
    [head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView);
        make.left.equalTo(headerView);
        make.right.equalTo(headerView);
        make.height.mas_equalTo(10);
    }];
    
    return headerView;
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
         
            return [UIImage imageNamed:@"购物车缺省页"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 24;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的购物车是空的哦!"),Localized(@"跟我去采一些吧。")]];
        
        
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的购物车是空的哦!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的购物车是空的哦!") length], [Localized(@"跟我去采一些吧。") length])];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithCart:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.tableview.contentOffset = CGPointZero;
}


#pragma mark 懒加载
-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate=self;
        _tableview.dataSource=self;
        _tableview.emptyDataSetSource = self;
        _tableview.emptyDataSetDelegate = self;
        _tableview.backgroundColor=[UIColor colorWithRed:0.93f green:0.94f blue:0.94f alpha:1.00f];
        _tableview.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableview.showsVerticalScrollIndicator=NO;
        _tableview.estimatedRowHeight = 0;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
    }
    return _tableview;
}
//- (NSString *)path {
//    if (!_path) {
//        _path = [[NSBundle mainBundle] pathForResource:@"cart" ofType:@"plist"];
//        NSLog(@"文件路径%@",_path);
//    }
//    return _path;
//}
#pragma mark - SEL
/**
 * 刷新购物车
 */
- (void)refreshCart {
    //    NSArray *plistArray = [HTPlistTool readPlistArrayWithPath:self.path].copy;
    //    _cartArray = [NSMutableArray array];
    //    for (int i = 0; i < plistArray.count; i++) {
    //        CartModel *cartModel = [CartModel yy_modelWithJSON:plistArray[i]];
    //        [_cartArray addObject:cartModel];
    //    }
    //    [self.tableview  reloadData];
}
/**
 * 单选商品
 */
- (void)clickSingleChooseButton:(UIButton *)button{
    button.selected = !button.selected;
    CartModel *cartModel = self.cartArray[button.tag / TAG_CELLBTN];
    CartDetailModel *dataolModel=cartModel.goods[button.tag-(button.tag / TAG_CELLBTN)*TAG_CELLBTN];
    
    dataolModel.chooseState = button.selected;
    BOOL shopAllChoosen = YES;
    for (CartDetailModel *detailModel in cartModel.goods) {
        shopAllChoosen &= detailModel.chooseState;
    }
    cartModel.chooseState = shopAllChoosen;
    
    BOOL allChoosen = YES;
    for (CartModel *cartModel in self.cartArray) {
        allChoosen &= cartModel.chooseState;
    }
    select.selected = allChoosen;
    [self updateBottomView];
    [self.tableview reloadData];

}
/**
 * 全选某商铺所有商品
 */
- (void)clickShopAllChooseButton:(UIButton *)button {
    button.selected = !button.selected;
    CartModel *cartModel = self.cartArray[button.tag / TAG_CELLBTN];
    //    CartDetailModel *dataolModel=cartModel.goods[button.tag-(button.tag / TAG_CELLBTN)*TAG_CELLBTN];
    cartModel.chooseState=button.selected;
    for (CartDetailModel *detailModel in cartModel.goods) {
        detailModel.chooseState = button.selected;
    }
    BOOL allChoosen = YES;
    for (CartModel *cartModel in self.cartArray) {
        allChoosen &= cartModel.chooseState;
    }
    select.selected = allChoosen;
    [self.tableview reloadData];
    [self updateBottomView];
}
/**
 * 全选商品
 */
- (void)clickAllChooseButton:(UIButton *)button {
    button.selected = !button.selected;
    for (CartModel *cartModel in self.cartArray) {
        cartModel.chooseState = button.selected;
        for (CartDetailModel *detailModel in cartModel.goods) {
            detailModel.chooseState = button.selected;
        }
    }
    [self.tableview reloadData];
    [self updateBottomView];
}
/**
 * 修改底部信息
 */
- (void)updateBottomView {
    CGFloat totalPrice = 0;
    for (CartModel *cartModel in self.cartArray) {
        for (CartDetailModel *detailModel in cartModel.goods) {
            if (detailModel.chooseState) {
                totalPrice += [detailModel.cart_num doubleValue] *[detailModel.cart_price floatValue];
            }
        }
    }
    _totalLabel.text = [NSString stringWithFormat:@"%@：¥%.2f",Localized(@"合计"),totalPrice];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:_totalLabel.text];
    //设置：在0-3个单位长度内的内容显示成红色
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [Localized(@"合计") length]+1)];
    _totalLabel.attributedText = str;
}
/**
 * 编辑所有商品
 */
- (void)editAllGoods:(UIBarButtonItem *)item {
    BOOL isEdit = [item.title isEqualToString:Localized(@"编辑")];
    _rightBarButtonItemTitle = isEdit ? Localized(@"完成") : Localized(@"编辑");
    self.tableview.scrollEnabled = !isEdit;
    [account setTitle:isEdit ? Localized(@"删除") : Localized(@"结算") forState:UIControlStateNormal];
    item.title = _rightBarButtonItemTitle;
    _isPressEditButton = isEdit;
    for (CartModel *cartModel in self.cartArray) {
        cartModel.isEdit = isEdit;
    }
    
    if (!isEdit) {
        for (NSString *key in self.numDict) {
            NSLog(@"%@---%@",key,self.numDict[key]);
            [self loadDataWithCartEdit:self.numDict[key] andUid:key];
        }
        [self.numDict removeAllObjects];
    }
    
    [self.tableview reloadData];
}

- (void)changeGoodsNumber:(NSInteger)num cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CartModel *cartModel = self.cartArray[indexPath.section];
    CartDetailModel *dataolModel=cartModel.goods[indexPath.row];
//    dataolModel.cart_num=[NSString stringWithFormat:@"%ld",(long)num];
    [self.numDict setObject:[NSString stringWithFormat:@"%ld",(long)num] forKey:dataolModel.uid];
}

- (void)loadDataWithCartEdit:(NSString *)num andUid:(NSString *)uid{
//    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
//    self.hud.detailsLabel.text =  Localized(@"加载中...");
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"cart/edit"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:num forKey:@"number"];
    [parametersDic setObject:uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
//         [self.hud hideAnimated:YES];
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                
                if ([responseDict[@"data"] isEqualToString:@"-2"]) {
                    [PublicClass ProgressHUDModeText:@"库存不足，修改失败" andTime:2 ];
                }
                if ([responseDict[@"data"] isEqualToString:@"1"]) {
                    [self loadDataWithCart:YES];
                }
            }
        }else{
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
       
    } andFailure:^{
//        [self.hud hideAnimated:YES];
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}

- (void)cartDetele:(UIButton *)but{
    CartModel *cartModel = self.cartArray[but.tag / TAG_CELLBTN];
    CartDetailModel *dataolModel=cartModel.goods[but.tag-(but.tag / TAG_CELLBTN)*TAG_CELLBTN];
    [self loadDataWithCartDetele:dataolModel.uid];
}
-(void)loadDataWithCartDetele:(NSString *)uid{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"cart/detele"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                
                if ([responseDict[@"data"] isEqualToString:@"1"]) {
                    [PublicClass ProgressHUDModeText:Localized(@"删除成功") andTime:2];
                    [self loadDataWithCart:YES];
                }
            }
        }else{
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
       
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}
-(NSMutableArray *)cartArray{
    if (!_cartArray) {
        _cartArray=[[NSMutableArray alloc]init];
    }
    return _cartArray;
}
-(NSMutableDictionary *)numDict{
    if (!_numDict) {
        _numDict=[[NSMutableDictionary alloc]init];
    }
    return _numDict;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

